//
//  BuyViewController.m
//  JiuJiuShangCheng
//
//  Created by jiujiukeji on 2018/7/13.
//  Copyright © 2018年 jiujiukeji. All rights reserved.
//

#import "ConfirmJiFenOrderViewController.h"
#import "SelectAddressTableViewCell.h"
#import "OrderTableViewCell.h"
#import "BuyItemTableViewCell.h"
#import "JiFenOrderDetailViewController.h"
#import "AddressModel.h"
#import "AddressViewController.h"

@interface ConfirmJiFenOrderViewController ()<UITableViewDelegate,UITableViewDataSource,AddressViewControllerDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSDictionary *jieSuanDic;
@property (nonatomic, strong) AddressModel *addressModel; // 选中地址
@property (nonatomic, strong) UITextField *textField;

@end

@implementation ConfirmJiFenOrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = tableViewBgColor;
    [self loadBaseTitleLable:@"确认订单"];
    [self.view addSubview:self.tableView];
    [self confirmOrder];
}
#pragma mark - 确认订单
- (void)confirmOrder
{
    if (self.selectId) {

        [MBProgressHUD showMessage:nil toView:self.view];
        NSString *code = [NSString stringWithFormat:@"%@%@",safeCode,[GetTimestamp getNowTimeTimestamp]];
        [TFNetworking postWithURLString:[NSString stringWithFormat:@"%@/api/json/shop/shop.ashx?action=integralexchange&companyid=%@&code=%@&timestamp=%@",kServerURL,companyId,[MD5Encrypt  MD5ForLower32Bate:code],[GetTimestamp getNowTimeTimestamp]] parameters:@{@"cartid":self.selectId,@"from":@"mobile"} success:^(id responseObject) {
            [MBProgressHUD hideHUDForView:self.view];
            if (responseObject) {
                if ([responseObject[@"status"] intValue] == 1) {
                    self.jieSuanDic = responseObject;
                    // 地址
                    if (responseObject[@"address"]) {
                        NSArray *array = responseObject[@"address"];
                        for (NSDictionary *dic in array) {
                            if ([dic[@"addressDefault"] intValue] == 1) {
                                // 默认地址
                                self.addressModel = [[AddressModel alloc] init];
                                [self.addressModel setValuesForKeysWithDictionary:dic];
                            }
                        }
                    }
                }
            }
            [self.tableView reloadData];
            
        } failure:^(NSError *error) {
            NSLog(@"%@",error);
            [TFHUD addRemindHUD:self.view message:@"保存失败,请检查网络"];
        }];
    }
}
#pragma mark - tableView delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    } else if (section == 1) {
        return 1;
    } else if (section == 2) {
        return 1;
    } else {
        return 1;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        SelectAddressTableViewCell *cell = [[SelectAddressTableViewCell alloc] init];
        // 赋值
        if (self.addressModel) {
            cell.nameLB.text = [NSString stringWithFormat:@"%@  %@",self.addressModel.addressName,self.addressModel.addressPhone];
            cell.addressLB.text = [NSString stringWithFormat:@"地址：%@%@%@%@",self.addressModel.addressProvince,self.addressModel.addressCity,self.addressModel.addressArea,self.addressModel.addressXX];
            if ([self.addressModel.addressDefault intValue] == 1) {
                cell.tagLB.hidden = NO;
            } else {
                cell.tagLB.hidden = YES;
            }
        }
        
        cell.selectionStyle = NO;
        return cell;
    } else if (indexPath.section == 1) {
        OrderTableViewCell *cell = [[OrderTableViewCell alloc] init];
        // 赋值
        NSArray *array = self.jieSuanDic[@"shopList"];
        if (array.count != 0) {
            NSDictionary *dic = array[0];

            [cell.goodsImg sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http:%@",dic[@"CartImg"]]]];
//            cell.goodsTitleLB.text = [NSString stringWithFormat:@"优惠金额：￥%.2f",[dic[@"CommodityYhPrice"] floatValue]];
            cell.describeLB.text = dic[@"CommodityProperty"];
            cell.priceLB.text = [NSString stringWithFormat:@"积分：￥%.2f",[dic[@"CommodityXPrice"] floatValue]];
            cell.numLB.text = [NSString stringWithFormat:@"×%@",dic[@"CommodityNumber"]];

        }
        cell.selectionStyle = NO;
        return cell;
    } else {
        BuyItemTableViewCell *cell = [[BuyItemTableViewCell alloc] init];
        if (indexPath.section == 2) {
            cell.leftLB.text = @"买家留言";
            cell.arrow.hidden = YES;
            cell.rightLB.hidden = YES;
            UITextField *textField = [[UITextField alloc] init];
            textField.placeholder = @"选填：对本次交易的说明";
            textField.font = UIFontSystem(13);
            textField.textColor = UIColorFromRGB(0x323232);
            [cell.contentView addSubview:textField];
            [textField mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(cell.contentView);
                make.left.equalTo(cell.leftLB.mas_right).offset(rateWidth(20));
                make.size.mas_offset(CGSizeMake(rateWidth(590), rateHeight(80)));
            }];
            self.textField = textField;
        } else {
            cell.redLB.hidden = NO;
            cell.arrow.hidden = YES;
            cell.rightLB.hidden = YES;
            cell.leftLB.text = @"合计积分：";
            cell.redLB.text = [NSString stringWithFormat:@"%@",self.jieSuanDic[@"totalPrice"]];
        }
        
        cell.selectionStyle = NO;
        return cell;
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return rateHeight(150);
    } else if (indexPath.section == 1) {
        return rateHeight(180);
    } else {
        return rateHeight(90);
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        return rateHeight(90);
    } else if (section == 2) {
        return rateHeight(2);
    } else {
        return 0.01;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        return rateHeight(10);
    } else if (section == 1) {
        return rateHeight(80);
    } else if (section == 3) {
        return rateHeight(200);
    } else {
        return rateHeight(10);
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *bgV = [[UIView alloc] init];
    if (section == 1) {
        bgV.backgroundColor = UIColorWhite;
        NSArray *array = self.jieSuanDic[@"shopList"];
        if (array.count != 0) {
            NSDictionary *dic = array[0];
            UILabel *label = [UILabel labelWithText:dic[@"CommodityName"] textColor:UIColorFromRGB(0x3b3b3b) fontSize:13];
            [label sizeToFit];
            [bgV addSubview:label];
            [label mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(bgV);
                make.left.equalTo(bgV).offset(rateWidth(25));
            }];
        }
    }
    return bgV;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *bgV = [[UIView alloc] init];
    if (section == 1) {
        bgV.backgroundColor = UIColorWhite;
        UILabel *label = [UILabel labelWithText:@"所需积分：100" textColor:UIColorFromRGB(0xf55555) fontSize:13];
        [label sizeToFit];
        [bgV addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(bgV);
            make.right.equalTo(bgV).offset(-rateWidth(40));
        }];
        
    } else if (section == 3) {
        bgV.backgroundColor = tableViewBgColor;
        UIButton *btn = [UIButton buttonWithTitle:@"提交订单" fontSize:14 titleColor:UIColorWhite background:navBarColor cornerRadius:5];
        [bgV addSubview:btn];
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(bgV);
            make.size.mas_offset(CGSizeMake(rateWidth(630), rateHeight(100)));
        }];
        [btn addTarget:self action:@selector(tiJiaoOrder) forControlEvents:(UIControlEventTouchUpInside)];
    }
    return bgV;
}
#pragma mark - 提交订单
- (void)tiJiaoOrder
{
    if (self.selectId) {

        [MBProgressHUD showMessage:nil toView:self.view];
        NSString *code = [NSString stringWithFormat:@"%@%@",safeCode,[GetTimestamp getNowTimeTimestamp]];
        [TFNetworking postWithURLString:[NSString stringWithFormat:@"%@/api/json/shop/shop.ashx?action=integralexchangesubmit&companyid=%@&code=%@&timestamp=%@",kServerURL,companyId,[MD5Encrypt  MD5ForLower32Bate:code],[GetTimestamp getNowTimeTimestamp]] parameters:@{@"cartid":self.selectId,@"addressid":self.addressModel.addresslId,@"remark":self.textField.text,@"from":@"mobile"} success:^(id responseObject) {
            [MBProgressHUD hideHUDForView:self.view];
            if (responseObject) {
                if ([responseObject[@"status"] intValue] == 1) {
                    JiFenOrderDetailViewController *jiFenDetailVC = [[JiFenOrderDetailViewController alloc] init];
                    jiFenDetailVC.ordersNumber = responseObject[@"orderNumber"];
                    [self.navigationController pushViewController:jiFenDetailVC animated:YES];
                } else {
                    [TFHUD addRemindHUD:self.view message:responseObject[@"returnMsg"]];
                }
            }

        } failure:^(NSError *error) {
            NSLog(@"%@",error);
            [TFHUD addRemindHUD:self.view message:@"保存失败,请检查网络"];
        }];

    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        // 收货地址
        AddressViewController *addressVC = [[AddressViewController alloc] init];
        addressVC.delegate = self;
        [self.navigationController pushViewController:addressVC animated:YES];
    }
}
#pragma mark - 地址 delegate
- (void)sendAddressModel:(AddressModel *)model
{
    self.addressModel = model;
    [self.tableView reloadData];
}
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, SafeAreaTopHeight, kScreenWidth, kScreenHeight-SafeAreaTopHeight) style:(UITableViewStyleGrouped)];
        _tableView.backgroundColor = tableViewBgColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = NO;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
    }
    return _tableView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
